package com.jinyuan.options.homepage;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.threadpool.IActivity;
import com.android.threadpool.Task;
import com.jinyuan.R;
import com.jinyuan.options.OptionsFragment;
import com.jinyuan.request.RequestURL;
import com.jinyuan.service.MobileApplication;
import com.jinyuan.service.TaskID;

/**
 * 首页
 * 
 * @author azuryleaves
 * @since 2014-1-8 上午11:23:18
 * @version 1.0
 * 
 */
public class HomePageFragment extends OptionsFragment implements IActivity {

	private View view;
	private TextView title_TextView, author_TextView, content_TextView;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		MobileApplication.allIActivity.add(this);
		setTitle(R.string.app_name);
		view = inflater.inflate(R.layout.homepage, container, false);
		init();
		Task task = new Task(TaskID.TASK_HOMEPAGE, RequestURL.getHomePage(),
				this.getClass().getName(), "-首页-");
		loadingDialog.show();
		MobileApplication.poolManager.addTask(task);
		return view;
	}

	private void initView(JSONObject jsonObject) {
		author_TextView.setVisibility(View.VISIBLE);
		try {
			title_TextView.setText(jsonObject.getString("name"));
			author_TextView.setText(jsonObject.getString("author"));
			content_TextView
					.setText(Html.fromHtml(jsonObject.getString("html")));
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void init() {
		title_TextView = (TextView) view
				.findViewById(R.id.homepage_title_TextView);
		author_TextView = (TextView) view
				.findViewById(R.id.homepage_author_TextView);
		content_TextView = (TextView) view
				.findViewById(R.id.homepage_content_TextView);
	}

	@Override
	public void refresh(int taskID, Object... params) {
		loadingDialog.cancel();
		if (params != null) {
			if (params[0] != null) {
				JSONObject jsonObject = (JSONObject) params[0];
				initView(jsonObject);
			} else {
				loadingDialog.showTimeOut();
			}
		} else {
			loadingDialog.showTimeOut();
		}
	}

	@Override
	public void closeLoadingView() {
		loadingDialog.cancel();
	}
}
